package utils

import (
	"errors"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
)

func UpdateDns(client *alidns.Client, domainName, recordType, ip string, recordName []string) (oldIp string, err error) {
	request := alidns.CreateDescribeDomainRecordsRequest()
	request.Scheme = "https"
	request.DomainName = domainName
	response, err := client.DescribeDomainRecords(request)
	if err != nil {
		return "", err
	}
	var recordID string
	var updateRequest = alidns.CreateUpdateDomainRecordRequest()
	for _, val := range recordName {
		for _, record := range response.DomainRecords.Record {
			if ip == record.Value {
				return oldIp, errors.New(fmt.Sprintf("IP未发生变化，无需做任何修改，当前记录值为：%s", record.Value))
			}
			if record.Type == recordType && record.RR == val {
				recordID = record.RecordId
				if recordID == "" {
					return "", errors.New(fmt.Sprintf("未找到记录： %s.%s", recordName, domainName))
				}

				updateRequest.Scheme = "https"
				updateRequest.RecordId = recordID
				updateRequest.RR = val
				updateRequest.Type = recordType
				updateRequest.Value = ip
				_, err = client.UpdateDomainRecord(updateRequest)
				oldIp = fmt.Sprintf("%s", record.Value)
				break
			}
		}
	}
	return oldIp, err
}
